package com.pearadmin.pro.common.tools.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pearadmin.pro.common.constant.TokenConstant;
import com.pearadmin.pro.common.security.subject.CustomUserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Describe: Json Web Token 工具类
 * Author: 就 眠 仪 式
 * CreateTime: 2019/10/23
 * */
public class TokenUtil {

    /**
     * Describe: 创建 Json Web Token
     * Param: UserDetails
     * Return: Token
     * */
    public static String createAccessToken(CustomUserDetails customUserDetails){

        return Jwts.builder()
                .setId(customUserDetails.getUserId())
                .setSubject(customUserDetails.getUsername())
                .setIssuedAt(new Date())
                .setIssuer(TokenConstant.ISSUER)
                .signWith(SignatureAlgorithm.HS512, TokenConstant.SECRET)
                .compact();
    }

    /**
     * Describe: 解析 Json Web Token
     * Param: token
     * Return: null
     * */
    public static CustomUserDetails parseAccessToken(String token){

        CustomUserDetails selfUserEntity = new CustomUserDetails();
        // 解析 Access Token
        Claims claims = Jwts.parser()
                .setSigningKey(TokenConstant.SECRET)
                .parseClaimsJws(token)
                .getBody();

        String username = claims.getSubject();
        String userId=claims.getId();
        selfUserEntity.setUserId(userId);
        selfUserEntity.setUserName(username);
        // 响 应 结 果
        return selfUserEntity;
    }
}
